import difference from 'lodash/difference';
/**
 * 判断是否有指定的操作权限
 * @param {array} permissions 权限数组
 * @param {string} option
 *
 * @example isHavePermission('add', pagePermissions, dataPermissions)
 */
export const isHavePermission = (option, ...permissions) => {
    if(permissions.some(p => !p || (p && p.length === 0)))
        return false;
    return permissions.every(p => p.includes(option));
};


export const computeSelectedRows = (preKeys, preRows, currentKeys, currentRows, keyIndex = 'id') => {
    if(currentKeys.length === 0)
        return [];
    // 勾选
    if(currentKeys.length > preKeys.length) {
        const newKeys = difference(currentKeys, preKeys);
        const newRows = [];
        newKeys.forEach(key => {
            const row = currentRows.find(r => r[keyIndex] === key);
            if(row)
                newRows.push(row);
        });
        return [...preRows, ...newRows];
    } else if(currentKeys.length < preKeys.length) { // 取消勾选
        const deleteKeys = difference(preKeys, currentKeys);
        const newRows = preRows.filter(d => !deleteKeys.includes(d[keyIndex]));
        return newRows;
    }
    return preRows;
};
